<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class osanMenu extends Model
{
    use HasFactory;

    protected $table = 'osan_menu';
    const STATUS_INVALID = 0;
    const STATUS_VALID = 1;

    /**
     * @return array
     */
    public static function getValidAllMenu(): array
    {
        return self::query()->where('status', self::STATUS_VALID)->get()->toArray();
    }

    /**
     * @param array $mid
     * @return array
     */
    public static function getTree(array $mid = []): array
    {
        $query = self::query()->whereIn('id', $mid)->where('status', self::STATUS_VALID);
        $rows = $query->get()->toArray();
        if (empty($rows)) {
            return [];
        }
        return self::genTree($rows, 'id', 'pid', 'sub_menu');
    }

    /**
     * convert to tree data
     * @return array
     */
    public static function genTree(array $list = [], string $key = 'id', string $pkey = 'pid', string $skey = 'sub'): array
    {
        $tree = [];
        $items = self::value2key($list, $key);
        foreach ($items as $item) {
            if (isset($items[$item[$pkey]])) {
                $items[$item[$pkey]][$skey][] = &$items[$item[$key]];
            } else {
                $tree[] = &$items[$item[$key]];
            }
        }
        return $tree;
    }

    /**
     * change value be key
     * @return array
     */
    public static function value2key(array $list = [], string $key = ''): array
    {
        $hash = [];
        if (!$key) {
            return $hash;
        }
        foreach ($list as $v) {
            isset($v[$key]) && $hash[$v[$key]] = $v;
        }

        return $hash;
    }
}
